package cn.skycity.auth.security.userdetails;

import cn.hutool.core.collection.CollectionUtil;
import cn.skycity.admin.pojo.entity.SysUser;
import cn.skycity.common.constants.GlobalConstants;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;


/**
 * @Author YingBo.Dai
 * 自定义userDetails
 */
@Data
public class SysUserDetails implements UserDetails {
    private Long userId;
    private String username;
    private String password;
    private int status;
    private Collection<SimpleGrantedAuthority> authorities;

    public SysUserDetails(SysUser user) {
        this.setUserId(user.getId());
        this.setUsername(user.getUsername());
        this.setPassword("{bcrypt}" + user.getPassword());
        this.setStatus(user.getStatus());
        if (CollectionUtil.isNotEmpty(user.getRoles())) {
            authorities = new ArrayList<>();
            user.getRoles().forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.status!=GlobalConstants.USER_EXPIRED;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.status!= GlobalConstants.USER_LOCK;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.status!=GlobalConstants.USER_FORBIDDEN;
    }
}
